package org.geekbang.thinking.in.spring.bean.definition;

import org.geekbang.thinking.in.spring.bean.factory.DefaultUserFactory;
import org.geekbang.thinking.in.spring.bean.factory.UserFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 *
 *
 */
@Configuration  // Configuration Class
public class BeanInitializationDemo {

    public static void main(String[] args) {
        // 创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册 Configuration Class（配置类）
        applicationContext.register(BeanInitializationDemo.class);
        // 启动 Spring 应用上下文
        applicationContext.refresh();

        // 非延迟初始化在 Spring 应用上下文启动完成后，被初始化
        System.out.println("Spring context 已启动...");

        UserFactory userFactory = applicationContext.getBean(UserFactory.class);
        System.out.println(userFactory);

        System.out.println("Spring context 准备关闭...");


        // 关闭 Spring 应用上下文
        applicationContext.close();
        System.out.println("Spring context 已关闭...");
    }

    // lazy-bean 在上下文启动后再执行初始化，而非 lazy-bean 在上下文启动前就完成初始化，两者在 Spring Context 上下文中的生命周期是不同的
    @Lazy(value = false)
    @Bean(initMethod = "initUserFactory", destroyMethod = "destroyUserFactory")
    public DefaultUserFactory userFactory() {
        return new DefaultUserFactory();
    }
}
